/**
 * CSV 导入/导出的工具类
 * @author rxliuli
 */
const csvUtil = (() => {
    const BOM = '\uFEFF'
    const separator = '\n'
    return new class CSVUtil {
        exportCSV(data, header) {
            return (
                BOM +
                Array.from(header.values()).join(',') +
                separator +
                _.chain(data)
                    .map(row =>
                        _.chain(Array.from(header.keys()))
                            .map(field => row[field])
                            .map(v => v + ',')
                            .join('')
                            .value(),
                    )
                    .map(s => s + separator)
                    .join('')
                    .value()
            )
        }

        importCSV(str, header) {
            let temp = str
            if (_.startsWith(str, BOM)) {
                temp = str.substring(BOM.length)
            }
            return (
                _.chain(temp.split('\n'))
                    .filter(row => row)
                    .map(row => row.split(','))
                    // 过滤掉首列标题
                    .filter(
                        (cols, i) =>
                            i !== 0 || !_.isEqual(cols, Array.from(header.values())),
                    )
                    // 映射为对象
                    .map(cols =>
                        Array.from(header.keys()).reduce((res, k, i) => {
                            res[k] = cols[i]
                            return res
                        }, {}),
                    )
                    .value()
            )
        }

        async importTextCSV(file, header) {
            const str = await rx.readLocal(file, {type: rx.readLocal.Text, encoding: 'gb2312'})
            if (str) {
                var array = await this.importCSV(str, header)
                array.splice(0, 1)
                return array
            }
            return null
        }

        async exportTextCSV(data, fileName, header) {
            const str = await this.exportCSV(data, header)
            rx.downloadString(str, fileName + '.csv')
        }

    }()
})()
